package spring;

import spring.annotation.Component;
import spring.annotation.Scope;

import java.lang.annotation.Annotation;

/**
 * @ProjectName: Spring
 * @Package: spring
 * @ClassName: AnnotatedBeanDefinitionReader
 * @Author: zxh
 * @Description: 用于读取注解
 * @Date: 2022/3/10 14:01
 * @Version: 1.0
 */
public class AnnotatedBeanDefinitionReader {

    private BeanDefinitionRegistry register;

    private AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();

    public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry register) {
        this.register = register;
        registerAnnotationConfigProcessors(this.register);
    }


    public void register(Class componentClass) {
        registerBean(componentClass);
    }

    public void registerBean(Class beanClass) {
        doRegisterBean(beanClass);
    }

    public void doRegisterBean(Class beanClass) {
        BeanDefinition bd = new BeanDefinition();
        String BeanName = beanNameGenerator.generateBeanName(beanClass);
        if (beanClass.isAnnotationPresent(Scope.class)) {
            Scope scope = (Scope) beanClass.getDeclaredAnnotation(Scope.class);
            bd.setScope(scope.value());
        } else {
            // 默认创建单实例对象
            bd.setScope("singleton");
        }
        bd.setClazz(beanClass);
        BeanDefinitionReaderUtils.registerBeanDefinition(new BeanDefinitionHolder(bd,BeanName),register);
    }

    private void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry){
        // 注册ConfigurationClassPostProcessor到Map中
        AnnotationConfigUtils.registerAnnotationConfigProcessors(registry);
    }


}
